package base.多线程.同步代码.消费者和生产者;

public class Consumer extends Thread{
    @Override
    public void run() {
        while(true){

            synchronized (Desk.lock){

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                if (Desk.count == 0){
                    System.out.println(getName()+"吃完10碗面条，打了一个饱嗝~");
                    break;
                }else {
                    if (Desk.foodFlag == 0){
                        //没有食物，需要等待
                        System.out.println("桌子上没有食物");
                        try {
                            Desk.lock.wait();//底层锁绑定当前线程
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        Desk.count--;
                        if (Desk.count != 0){
                            System.out.println(getName()+"好饿~还想吃"+Desk.count+"碗面条！");
                        }

                        Desk.foodFlag = 0;
                        Desk.lock.notifyAll();
                    }
                }
            }
        }
    }
}
